module ResourcesHelper

 def geTFavoriteResources(userId , resourceId)
  favorites = Favorite.find(:all , :conditions => "user_id = #{userId} AND resource_id = #{resourceId}")
  
 end
 
 def Resource.multiTagQuery(multiple_tags,tag) 
		if(!multiple_tags.include?(tag.id)) then
			multiple_tags << tag.id
		end
	 	recommendeTagsQueryInitial = " T.tag_id = "
    	recommendeTagsQuery = ""
    	counter = 0
    	while(counter < (multiple_tags.length - 1)) do 
    		recommendeTagsQuery += recommendeTagsQueryInitial + (multiple_tags[counter]).to_s + " OR "
    		counter += 1
    	end
    	recommendeTagsQuery += recommendeTagsQueryInitial + (multiple_tags[counter]).to_s
    	finalRecommendedQuery = "(" + recommendeTagsQuery + ")"
		query =  "SELECT R.id, R.title, R.link , R.description ,R.user_id, R.created_at , R.updated_at FROM resources R, tag_events T WHERE #{finalRecommendedQuery} AND T.resource_id = R.id;"
		return query
 end
 
 def Resource.resourcesForMultipleTags(multiple_tags,resources)
#  	if(!multiple_tags.nil?) then
		provResource = []
		if(resources.length > 0) then resId = (resources[0]).id end;
	 	resourceCounter = 0
# 	 	flash[:notice] = (multiple_tags.length).to_s + ": " +(resources.length).to_s + ", " + resId.to_s
	 	countAll = 0
		resources.each {|res|  
			countAll += 1
# 			flash[:notice] << " NOW id: "+ (res.id).to_s

			if(res.id == resId) then
				resourceCounter += 1
# 				flash[:notice] << " "+ (res.id).to_s
			else
				resId = res.id
				resourceCounter = 1
			end
	
			if(resourceCounter >= multiple_tags.length) then
				provResource << res
				resourceCounter = 1
# 				flash[:notice] << " ADDED "
			end
		}
# 		flash[:notice] << ". ALL: "+ countAll.to_s
		resources = provResource
		return resources
# 	end
 end
 
 def Resource.recommendedQuery(userId)
   	query = "Select T.name, T.id from tags T, interests I where I.user_id = '#{userId}' AND T.id = I.tag_id;"
    tags = Tag.find_by_sql(query)
    if(tags.nil?) then
    	tags = []
    end
    recommendeTagsQueryInitial = " T.tag_id = "
    recommendeTagsQuery = ""
    counter = 0
    while(counter < tags.length-1) do 
 		recommendeTagsQuery += recommendeTagsQueryInitial + (tags[counter].id).to_s + " OR "
   		counter += 1
   	end
    recommendeTagsQuery += recommendeTagsQueryInitial + (tags[tags.length-1].id).to_s
    finalRecommendedQuery = "(" + recommendeTagsQuery + ")"
 	query =  "SELECT DISTINCT R.id, R.title, R.link , R.description ,R.user_id, R.created_at , R.updated_at FROM resources R, tag_events T , Grades G WHERE #{finalRecommendedQuery} AND T.resource_id = R.id AND R.id = G.resource_id ORDER BY G.evaluation DESC;"
 	return query
 end
end
